using System.Globalization;
using Godot;
using kemocard.Scripts.Common;

namespace kemocard.Components.FloatingText;

public partial class FloatingText : Node2D
{
    [Export] private Label _lab;
    private Tween _tween;
    private float _value;

    public override void _Ready()
    {
        base._Ready();
        Scale = Vector2.Zero;
        DisplayFloatingText();
    }

    private void DisplayFloatingText()
    {
        if (_tween != null && _tween.IsRunning())
        {
            _tween.Kill();
        }

        _lab.Text = _value.ToString(CultureInfo.InvariantCulture);
        _tween = CreateTween();
        _tween.SetParallel();

        _tween.TweenProperty(this, "global_position", GlobalPosition + Vector2.Up * 40, .3f);
        _tween.TweenProperty(this, "scale", Vector2.One, .3f).SetEase(Tween.EaseType.Out)
            .SetTrans(Tween.TransitionType.Elastic);
        _tween.Chain();
        _tween.TweenProperty(this, "global_position", GlobalPosition + Vector2.Up * 80, .4f);
        _tween.TweenProperty(this, "scale", Vector2.Zero, .4f);
        _tween.Chain();
        _tween.TweenCallback(Callable.From(QueueFree));
        _tween.Play();
    }

    public static FloatingText New(Node parent, float value)
    {
        var res = ResourceLoader.Load<PackedScene>("res://Components/FloatingText/FloatingText.tscn");
        if (res == null || parent == null) return null;
        var text = res.Instantiate<FloatingText>();
        text._value = value;
        parent.AddChild(text);
        return text;
    }
}